package org.lc.cmd.connect.impl;

import org.lc.cmd.CmdContext;
import org.lc.cmd.connect.CmdContextManager;
import org.springframework.stereotype.Component;

@Component
public class DefaultCmdContextManager implements CmdContextManager, CmdContextSetter {
    private static final ThreadLocal<CmdContext> CURRENT_CONTEXT = new ThreadLocal<>();

    @Override
    public void setCurrentContext(CmdContext context) {
        CURRENT_CONTEXT.set(context);
    }

    @Override
    public void clearCurrentContext() {
        CURRENT_CONTEXT.remove();
    }

    @Override
    public CmdContext getCurrentContext() {
        return CURRENT_CONTEXT.get();
    }

    /**
     * 复制上下文，使上下文在新线程可用
     *
     * @param runnable 待执行的异步任务
     * @return 改造后的新任务
     */
    public Runnable copyContext(Runnable runnable) {
        CmdContext context = getCurrentContext();
        return () -> {
            try {
                setCurrentContext(context);
                runnable.run();
            } finally {
                // 清理上下文，避免线程池中使用时污染后续任务
                clearCurrentContext();
            }
        };
    }
}
